package com.fa4j.common.web.controller;

import com.fa4j.common.web.model.ResponseVO;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/error")
public class ErrorController extends AbstractErrorController {

    public ErrorController(ErrorAttributes errorAttributes, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorViewResolvers);
    }

    @Operation(hidden = true)
    @RequestMapping
    public ResponseVO<?> error(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> attributes = getErrorAttributes(request, ErrorAttributeOptions.defaults());
        HttpStatus status = this.getStatus(request);
        String path = request.getRequestURI();
        String errMsg = (String) attributes.get("error");
        ResponseVO<?> result = new ResponseVO<>();
        result.setSuccess(false);
        result.setErrCode(status.value());
        result.setErrMsg(status.getReasonPhrase());
        if (status.is5xxServerError()) {
            log.error("[{}]<<==!: {}-{}", path, status, errMsg);
        } else {
            log.warn("[{}]<<==!: {}-{}", path, status, errMsg);
        }
        return result;
    }

}
